package com.example.security2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        //默认加密(自己不指定)，数据库中必须有前缀{id}
        //自配置加密，数据库中无需前缀{id}
        return new BCryptPasswordEncoder();
    }

    @Bean//登录时需要调用 AuthenticationManager.authenticate()方法进行一次校验
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {

        return config.getAuthenticationManager();//返回providerManager
    }
    @Bean//1.登录请求放(安全框架默认所有路径均受默认保护，都会跳到框架内置的login页面)
    //让login路径失去框架的保护，让其可以直接访问
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable());
        http.authorizeHttpRequests(auth -> auth.requestMatchers("/login")
                .permitAll()
                .anyRequest().authenticated()
        );
        return http.build();
    }

}
